/**
 * Module dependencies.
 */

var express = require('express');
// var engines = require('consolidate');

var path = require('path');
var url = require('url');
var fs = require('fs');
var domain = require('domain');
var config = require('./config');
var auth = require('../middlewares/auth');
var site = require('./site');
// var responseTime = require('../middlewares/responseTime');
var responseTime = require('response-time');

var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var compress = require('compression');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');
var MongoStore = require('connect-mongo')(session);

/**
 * Expose Configuration scope
 */

module.exports = appCfg;

/**
 * Applies configurations settings for application.
 *
 * @param {Express}
 *            app `Express` instance.
 * @api public
 */

function appCfg(app) {
	// all environments
	app.set('port', process.env.PORT || config.app.port);
	app.set('views', path.join(__dirname, '..', '/views'));
	app.set('view engine', config.app.viewEngine);
	// app.set('view engine', 'html');
	// app.engine('html', require('ejs').renderFile);
	// app.engine('ejs', engines.ejs);
	// app.engine('html', engines.hogan);
	app.set('site', site);
	app.use(favicon(path.join(__dirname, '..', '/public/favicon.ico')));
	app.use(logger('dev'));
	app.use(methodOverride('_method'));
	app.use(compress());
	app.use(cookieParser(config.session.secret));
	app.use(session({
		key: 'sid',
		store: new MongoStore({
			url: config.db
		}),
		resave: true,
		saveUninitialized: true,
		secret: config.session.secret
	}));
	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	// 解析multipart/form-data表单 @See https://www.npmjs.org/package/multer
	app.use(multer({
		dest: '/public/uploads',
		limits: {
			fileSize: 10240
		}
	}));
	app.use(express.static(path.join(__dirname, '..', '/public')));
	// app.use(express.csrf());
	// app.use(function(req, res, next){
	// 	res.locals.req = req;
	// 	res.locals.session = req.session;
	// 	res.locals.csrf = req.csrfToken() || '';
	// 	next();
	// });
	// 响应时间
	app.use(responseTime());
	// 全局异常处理
	// 使用 domain 来捕获大部分异常
	app.use(function(req, res, next) {
		var reqDomain = domain.create();
		reqDomain.on('error', function() {
			try {
				var killTimer = setTimeout(function() {
					process.exit(1);
				}, 30000);
				killTimer.unref();
				server.close();
				res.send(500);
			} catch (e) {
				console.log('error when exit', e.stack);
			}
		});

		reqDomain.run(next);
	});
	// uncaughtException 避免程序崩溃
	// process.on('uncaughtException', function (err) {
	// 	console.log(err);
	// 	try {
	// 		var killTimer = setTimeout(function () {
	// 			process.exit(1);
	// 		}, 30000);
	// 		killTimer.unref();

	// 		server.close();
	// 	} catch (e) {
	// 		console.log('error when exit', e.stack);
	// 	}
	// });

	// 登陆用户放入locals
	app.use(auth.authUser);

	// app.use(app.router);

	// error handler
	if (config.debug) {
		app.use(errorHandler());
	} else {
		app.use(function(err, req, res, next) {
			return res.send(500, '500 status');
		});
	}

}